<template>
  <div class="shopping-cart-page">
    <!-- 导航栏 -->
    <NavBar />
    <userinfo></userinfo>
    
    <!-- 搜索框 -->
    <div class="search-container">
      <div class="search-bar">
        <select v-model="searchType" class="search-select">
          <option value="product">Product</option>
          <option value="store">Store</option>
        </select>
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="Search for store or product..." 
          class="search-input"
        />
        <button @click="search" class="search-button">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M10 2a8 8 0 016.32 12.906l4.387 4.387-1.414 1.414-4.387-4.387A8 8 0 1110 2zm0 2a6 6 0 100 12 6 6 0 000-12z"></path>
          </svg>
        </button>
      </div>
    </div>

    <!-- 购物车内容 -->
    <div class="cart-content">
      <!-- 购物车列表 -->
      <div class="cart-container">
        <div class="cart-header">
          <h2 class="cart-title">Your Shopping Cart</h2>
          <p class="cart-subtitle">{{ cart.length }} items in your cart</p>
        </div>
        
        <div v-if="cart.length === 0" class="empty-cart">
          <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M3 7l3-3h12l3 3m-6-3v18m-6-3a3 3 0 1 0 6 0 3 3 0 0 0-6 0z"></path>
          </svg>
          <h3>Your cart is empty</h3>
          <p>Start shopping to add items to your cart</p>
          <button @click="$router.push('/')" class="shop-button">Continue Shopping</button>
        </div>
        
        <div v-else class="cart-list">
          <div v-for="item in cart" :key="item.goodsId" class="cart-item">
            <div class="item-image-container">
              <img 
                :src="getProductImage(item.goodsId)" 
                :alt="item.goodsId" 
                class="item-image"
                loading="lazy"
              />
            </div>
            
            <div class="item-details">
              <h3 class="item-name">Product #{{ item.goodsId }}</h3>
              <p class="item-price">¥{{ safeToFixed(item.price) }}</p>
              
              <div class="quantity-controls">
                <button @click="decreaseQuantity(item)" class="quantity-btn">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="M5 12h14"></path>
                  </svg>
                </button>
                <span class="quantity">{{ item.number }}</span>
                <button @click="increaseQuantity(item)" class="quantity-btn">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path d="M12 5v14M5 12h14"></path>
                  </svg>
                </button>
              </div>
              
              <p class="item-subtotal">Subtotal: ¥{{ safeToFixed(item.totalPrice) }}</p>
            </div>
            
            <button @click="removeFromCart(item.goodsId)" class="remove-button">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <path d="M18 6L6 18M6 6l12 12"></path>
              </svg>
            </button>
          </div>
        </div>
      </div>

      <!-- 结算区域 -->
      <div class="checkout-summary">
        <div class="summary-header">
          <h3>Order Summary</h3>
        </div>
        
        <div class="summary-details">
          <div class="summary-row">
            <span>Subtotal</span>
            <span>¥{{ safeToFixed(subtotal) }}</span>
          </div>
          <div class="summary-row">
            <span>Shipping</span>
            <span>Free</span>
          </div>
          <div class="summary-row total">
            <span>Total</span>
            <span>¥{{ safeToFixed(totalPrice) }}</span>
          </div>
        </div>
        
        <button @click="checkout" class="checkout-button">Proceed to Checkout</button>
        

      </div>
    </div>

    <!-- 支付方式弹窗 -->
    <transition name="modal-fade">
      <div v-if="showPaymentModal" class="payment-modal">
        <div class="payment-modal-content">
          <h3>Select Payment Method</h3>

          <div class="payment-options">
            <button @click="selectPayment('wechat')" class="payment-option">
              <div class="payment-icon">
                <img src="@/assets/payment/wechat.png" alt="WeChat Pay" />
              </div>
              <span>WeChat Pay</span>
            </button>

            <button @click="selectPayment('alipay')" class="payment-option">
              <div class="payment-icon">
                <img src="@/assets/payment/alipay.png" alt="Alipay" />
              </div>
              <span>Alipay</span>
            </button>

            <button @click="selectPayment('unionpay')" class="payment-option">
              <div class="payment-icon">
                <img src="@/assets/payment/unionpay.png" alt="UnionPay" />
              </div>
              <span>UnionPay</span>
            </button>
          </div>

          <button @click="showPaymentModal = false" class="cancel-button">
            Cancel
          </button>
        </div>
      </div>
    </transition>

    <!-- 支付成功弹窗 -->
    <transition name="modal-fade">
      <div v-if="showSuccessModal" class="success-modal">
        <div class="success-modal-content">
          <div class="success-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
              <path d="M22 4L12 14.01l-3-3"></path>
            </svg>
          </div>
          <h3>Payment Successful!</h3>
          <p>Your order has been placed and will be processed shortly.</p>
          <button @click="showSuccessModal = false" class="success-button">
            Continue Shopping
          </button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import NavBar from "@/components/NavBar.vue";
import store from "@/store";
import router from "@/router";
import userinfo from "@/components/UserInfo.vue";

const searchQuery = ref("");
const searchType = ref("product");
const cart = ref([]);
const showPaymentModal = ref(false);
const showSuccessModal = ref(false);
const selectedPayment = ref("");

// 计算属性
const subtotal = computed(() => {
  return cart.value.reduce((sum, item) => sum + (Number(item.price) || 0) * (item.number || 1), 0);
});

const totalPrice = computed(() => {
  return subtotal.value; // 这里可以加上运费等
});

// 方法
const safeToFixed = (value) => {
  const num = Number(value);
  return isNaN(num) ? "0.00" : num.toFixed(2);
};

const getProductImage = () => {
  return `https://avatars.mds.yandex.net/i?id=95043d420b85d6a9a714afc26c1357f78d6003f5-9678500-images-thumbs&n=13`;
};

const fetchCartData = async () => {
  if (!store.getters['user/username']) {
    alert("Please login first");
    router.push("/userLogin");
    return;
  }

  try {
    const response = await axios.get("http://localhost:8080/api/cart/list", {
      params: { user_name: store.getters['user/username'] }
    });

    const itemsArray = response.data.data || 
                      response.data.items || 
                      (Array.isArray(response.data) ? response.data : []);

    if (!Array.isArray(itemsArray)) {
      throw new Error("无法从响应中提取数组数据");
    }

    cart.value = itemsArray.map(item => ({
      ...item,
      totalPrice: item.totalPrice || (item.price || 0) * (item.number || 1)
    }));

  } catch (error) {
    console.error("获取购物车数据失败:", error);
    cart.value = [];
  }
};

const increaseQuantity = async (item) => {
  try {
    let res = await axios.put('http://localhost:8080/api/cart/increase?goodsId='+item.goodsId);
    item.number++;
    item.totalPrice = (item.price || 0) * item.number;
    console.log(res);
  } catch (error) {
    console.error("Failed to increase quantity", error);
  }
};

const decreaseQuantity = async (item) => {
  if (item.number <= 1)  {
    removeFromCart(item.goodsId);
    return;
  } 
  
  try {
    await axios.put('http://localhost:8080/api/cart/decrease?goodsId='+item.goodsId);
    item.number--;
    item.totalPrice = (item.price || 0) * item.number;
  } catch (error) {
    console.error("Failed to decrease quantity", error);
  }
};

const removeFromCart = async (goodsId) => {
  try {
    await axios.delete(`http://localhost:8080/api/cart/delete?user_name=`+store.getters['user/username']+'&goodsId='+goodsId);
    cart.value = cart.value.filter(item => item.goodsId !== goodsId);
  } catch (error) {
    console.error("Failed to remove item", error);
  }
};

const postOrder = async (item) => {
  let sellerName = store.getters['seller/orderid'].get(item.goodsId);
  console.log('sellerName:',sellerName);
  try {
    let res = await axios.post(`http://localhost:8080/api/order/create?goodsId=${item.goodsId}&sellerName=${sellerName}&number=${item.number}`);
    return res
  } catch (error) {
    console.error("Failed to post order", error);
  } 
}

const checkout = () => {
  if (cart.value.length === 0) {
    alert("Your cart is empty");
    return;
  }
  showPaymentModal.value = true;
};

const selectPayment = (method) => {
  selectedPayment.value = method;
  showPaymentModal.value = false;
  
  // 模拟支付过程
  setTimeout(() => {
    completePayment();
  }, 1500);
};

const createUserOrder = (item,orderid)=>{
  console.log('seller:',store.getters['seller/orderid'].get(item.goodsId));
  let seller = store.getters['seller/orderid'].get(item.goodsId);
  let goodsname = store.getters['seller/goodsname'].get(item.goodsId);
  axios.post(`http://localhost:8080/api/userOrder/create?username=${store.getters['user/username']}&orderid=${orderid}&seller=${goodsname}&goods=${seller}`)
  .then(res=>{
    console.log(res);
  })
  .catch(err=>{
    console.log(err);
  })
}

const completePayment = async () => {
  try {
    // 提交所有订单
    for (let item of cart.value) {
      let res = await postOrder(item);
      await removeFromCart(item.goodsId);
      console.log('res:',res);
      await createUserOrder(item,res.data.msg);
    }
    
    // 显示支付成功
    showSuccessModal.value = true;
    
    // 3秒后自动关闭成功提示
    setTimeout(() => {
      showSuccessModal.value = false;
    }, 3000);
    
  } catch (error) {
    console.error("支付过程中出错:", error);
    alert("支付失败，请重试");
  }
};

onMounted(fetchCartData);
</script>

<style scoped>
/* 基础变量 */
:root {
  --primary-color: #4f46e5;
  --primary-light: #6366f1;
  --primary-dark: #4338ca;
  --success-color: #10b981;
  --danger-color: #ef4444;
  --text-color: #1f2937;
  --text-light: #6b7280;
  --border-color: #e5e7eb;
  --bg-color: #f9fafb;
  --card-bg: #ffffff;
  --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  --transition: all 0.3s ease;
}

.shopping-cart-page {
  min-height: 100vh;
  background-color: var(--bg-color);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
  color: var(--text-color);
}

/* 搜索框样式 */
.search-container {
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  padding: 1.5rem;
  margin-bottom: 2rem;
}

.search-bar {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  gap: 1rem;
  background-color: white;
  border-radius: 12px;
  padding: 0.5rem 1rem;
  box-shadow: var(--shadow-md);
}

.search-select {
  appearance: none;
  background-color: white;
  border: none;
  border-radius: 8px;
  padding: 0.5rem 1rem;
  font-size: 0.9rem;
  font-weight: 500;
  color: var(--primary-color);
  cursor: pointer;
  box-shadow: var(--shadow-sm);
  transition: var(--transition);
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 0.75rem center;
  background-size: 1rem;
}

.search-input {
  flex: 1;
  border: none;
  padding: 0.5rem;
  font-size: 0.95rem;
  outline: none;
}

.search-button {
  background: none;
  border: none;
  color: var(--primary-color);
  cursor: pointer;
  padding: 0 0.5rem;
  transition: var(--transition);
}

.search-button:hover {
  color: var(--primary-dark);
}

/* 购物车内容布局 */
.cart-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1.5rem 2rem;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 2rem;
}

/* 购物车列表样式 */
.cart-container {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: var(--shadow-sm);
}

.cart-header {
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid var(--border-color);
}

.cart-title {
  font-size: 1.5rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
}

.cart-subtitle {
  font-size: 0.875rem;
  color: var(--text-light);
}

.empty-cart {
  text-align: center;
  padding: 3rem 0;
}

.empty-cart svg {
  stroke: #d1d5db;
  margin-bottom: 1rem;
}

.empty-cart h3 {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.empty-cart p {
  color: var(--text-light);
  margin-bottom: 1.5rem;
}

.shop-button {
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 0.75rem 1.5rem;
  font-weight: 500;
  cursor: pointer;
  transition: var(--transition);
}

.shop-button:hover {
  background-color: var(--primary-dark);
}

/* 购物车商品项 */
.cart-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.cart-item {
  display: grid;
  grid-template-columns: 100px 1fr auto;
  gap: 1.5rem;
  padding: 1rem;
  border-radius: 8px;
  transition: var(--transition);
  position: relative;
}

.cart-item:hover {
  background-color: #f9fafb;
}

.item-image-container {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  overflow: hidden;
}

.item-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: var(--transition);
}

.cart-item:hover .item-image {
  transform: scale(1.05);
}

.item-details {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 1rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.item-price {
  font-size: 0.875rem;
  color: var(--text-light);
  margin-bottom: 0.5rem;
}

.item-subtotal {
  font-weight: 600;
  color: var(--primary-color);
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 0.5rem 0;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: 1px solid var(--border-color);
  background: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: var(--transition);
}

.quantity-btn:hover {
  background-color: #f3f4f6;
  border-color: var(--primary-light);
}

.quantity {
  min-width: 24px;
  text-align: center;
  font-weight: 500;
}

.remove-button {
  background: none;
  border: none;
  color: var(--text-light);
  cursor: pointer;
  transition: var(--transition);
  align-self: flex-start;
}

.remove-button:hover {
  color: var(--danger-color);
}

/* 结算区域 */
.checkout-summary {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: var(--shadow-sm);
  align-self: flex-start;
  position: sticky;
  top: 1rem;
}

.summary-header {
  padding-bottom: 1rem;
  border-bottom: 1px solid var(--border-color);
  margin-bottom: 1rem;
}

.summary-header h3 {
  font-size: 1.25rem;
  font-weight: 600;
}

.summary-details {
  margin-bottom: 1.5rem;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.75rem;
  font-size: 0.875rem;
}

.summary-row.total {
  font-weight: 600;
  font-size: 1rem;
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid var(--border-color);
}

.checkout-button {
  width: 100%;
  background: linear-gradient(135deg, #4f46e5, #7c3aed); /* 渐变色 */
  color: white;
  padding: 16px;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  margin-top: 20px;
}

.checkout-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(79, 70, 229, 0.25);
}

.checkout-button:hover {
  background-color: var(--primary-dark);
}

.payment-methods {
  display: flex;
  justify-content: center;
  gap: 1rem;
}

.payment-methods img {
  height: 24px;
  opacity: 0.7;
  transition: var(--transition);
}

.payment-methods img:hover {
  opacity: 1;
}

/* 模态框样式 */
.modal-fade-enter-active,
.modal-fade-leave-active {
  transition: opacity 0.3s ease;
}

.modal-fade-enter-from,
.modal-fade-leave-to {
  opacity: 0;
}

.payment-modal,
.success-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(29, 25, 32, 0.5);
  
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.payment-modal-content,
.success-modal-content {
  background-color: #594b636e;
  border: 1px solid #100d12;
  border-radius: 12px;
  padding: 2rem;
  width: 100%;
  max-width: 400px;
  box-shadow: var(--shadow-lg);
  text-align: center;
}

.payment-modal-content h3,
.success-modal-content h3 {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 1.5rem;
}

.success-modal-content p {
  color: var(--text-light);
  margin-bottom: 1.5rem;
}

.payment-options {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.payment-option {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background: none;
  cursor: pointer;
  transition: var(--transition);
  text-align: left;
}

.payment-option:hover {
  border-color: var(--primary-light);
  background-color: #f5f3ff;
}

.payment-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-icon img {
  max-width: 100%;
  max-height: 100%;
}

.cancel-button,
.success-button {
  width: 100%;
  padding: 0.75rem;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: var(--transition);
}

.cancel-button {
  background: none;
  border: 1px solid var(--border-color);
  margin-top: 1rem;
}

.cancel-button:hover {
  background-color: #f3f4f6;
}

.success-button {
  background-color: var(--primary-color);
  color: white;
  border: none;
}

.success-button:hover {
  background-color: var(--primary-dark);
}

.success-icon {
  color: var(--success-color);
  margin-bottom: 1rem;
}

.success-icon svg {
  stroke-width: 2;
}
</style>
